//
//  CarNewsViewController.m
//  小汽车
//
//  Created by 杜远洋 on 14-12-29.
//  Copyright (c) 2014年 蓝欧科技. All rights reserved.
//

#import "CarNewsViewController.h"
#import "AFJSONRequestOperation.h"
#import "CarNewsCollectionViewCell.h"
#import "CarNewsModel.h"
#import "SortModel.h"
#import "DetailNewsViewController.h"
#import "Masonry.h"
#import "MarketAreaViewController.h"

@interface CarNewsViewController ()<UICollectionViewDataSource, UICollectionViewDelegate,CarNewsCollectionViewCellDelegate>

@end

@implementation CarNewsViewController
- (void)dealloc
{
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"changeState" object:nil];
    [_scroll release];
    [_button release];
    [_collectArray release];
    [_collection release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.collectArray = [NSMutableArray array];
        self.buttonArray = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];

//    [self NotificationCenter];
#pragma mark - 有时候坐标出现偏移，就要调整这个属性，设置为NO;
  
    //self.automaticallyAdjustsScrollViewInsets = NO;
    [self myConnection];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, 20, 20)];
    [titleLabel setText:@"小汽车"];
    [titleLabel setTextColor: [UIColor whiteColor]];
    [titleLabel setFont:[UIFont fontWithName:@"CourierNewPS-BoldItalicMT" size:22]];
    [self.navigationItem setTitleView:titleLabel];
    
   

    
    
}

- (void)myConnection
{
  
    
    for (int i = 0; i < 5; i ++) {
        if (i == 2) {
            NSString *str = [NSString stringWithFormat:@"http://wap.xcar.com.cn/cms/interface/5.0/getNewsList.php?limit=10&offset=0&type=2&ver=5.3.4"];
            [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
            NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
           
            //从url获取json数据
            AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id  JSON) {
                NSArray *array = [JSON objectForKey:@"news"];
                SortModel *sortModel = [[SortModel alloc] init];
                for (NSDictionary *dic in array) {
                    CarNewsModel *model = [[CarNewsModel alloc] init];
                    model.newsTitle = [dic objectForKey:@"newsTitle"];
                    model.createDates = [self getLocalTime];
                    
#pragma mark - 根据modelid进行自定义cell的设置，标记出来特殊的，然后进行处理
                    
                    model.markedId = i;
                    model.newsLink = [dic objectForKey:@"newsLink"];
                    [sortModel.myArray addObject:model];
                    [model release];
                    
                }
#pragma mark - 根据id进行排序，否则会乱，排序完事之后，在进行向下一页传值
                
                sortModel.modelId = i;
                [self.collectArray addObject:sortModel];
                [sortModel release];
                
                [self.collection reloadData];
                NSLog(@"数据解析成功");
            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                NSLog(@"%@",error);
                NSLog(@"数据解析失败  ~~~");
            }];
            
            [operation start];
        }
        else
        {
            
            
            NSString *str = [NSString stringWithFormat:@"http://wap.xcar.com.cn/cms/interface/5.0/getNewsList.php?limit=10&offset=0&type=%d&ver=5.3.4",i];
            [AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"text/html"]];
            NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
        
            AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
                NSArray *array = [JSON objectForKey:@"news"];
                SortModel *sortModel = [[SortModel alloc] init];
                for (NSDictionary *dic in array) {
                    CarNewsModel *model = [[CarNewsModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic];
                    model.markedId = i;
                    NSNumber *comment = [dic objectForKey:@"comment"];
                    NSString *myComment = [NSString stringWithFormat:@"%@",comment];
                    model.comments = myComment;
                    model.createDates = [self getLocalTime];
                    [sortModel.myArray addObject:model];
                    [model release];
                }
                
                sortModel.modelId = i;
                [self.collectArray addObject:sortModel];
                [sortModel release];
                
                [self.collection reloadData];
                NSLog(@"解析数据成功");

            } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
                NSLog(@"%@",error);
                NSLog(@"解析数据失败");
            }];
            [operation start];
        
        }
    }
    
    
    [self createCarNews];
  

    
}

- (NSString *)getLocalTime
{
    NSDate *dates = [NSDate date];
    NSDateFormatter *formatter =  [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/beijing"];
    [formatter setTimeZone:timeZone];
    NSString *localTime = [formatter stringFromDate:dates];
   
    return localTime;
    
}


#pragma mark - 每次排序，防止网络连接的快慢造成顺序紊乱

- (NSMutableArray *)sortUseBlock:(NSArray *)array
{
    NSMutableArray *myArray = [NSMutableArray arrayWithArray:array];
    [myArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        
        SortModel *first = (SortModel *)obj1;
        SortModel *second = (SortModel *)obj2;
        if (first.modelId > second.modelId) {
            return NSOrderedDescending;
        }
        else if (first.modelId == second.modelId)
        {
            return NSOrderedSame;
        }
        else
        {
            return NSOrderedAscending;
        }
    }];
    return myArray;
}


- (void)changeBackGroundColor
{
    
#pragma mark - 修改scroll 的夜间模式 （夜间模式都用NSUserDefaults来修改）
    NSUserDefaults *myNight = [NSUserDefaults standardUserDefaults];
    if ([[myNight objectForKey:@"night"] isEqualToString:@"0"]) {
        [self.view setBackgroundColor:[UIColor whiteColor]];
    }
    else
    {
        self.view.backgroundColor = [UIColor colorWithRed:54/255.0f green:54/255.0f blue:54/255.0f alpha:1];
    }

}

- (void)createCarNews
{


    
#pragma mark - scrollView上放button 来实现点击跳转页面的事件
    
    
    
    NSArray *array = [NSArray arrayWithObjects:@"最新",@"新车",@"行情",@"评测",@"导购", nil];
    self.scroll = [UIScrollView new];

     [self.view addSubview:self.scroll];

    __block UIViewController *weakSelf = self;

    [self.scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(@(weakSelf.view.frame.size.width));
        make.height.mas_equalTo(@(30));
    }];
    [self.scroll setBackgroundColor:[UIColor colorWithRed:238/255.0f green:233/255.0f blue:233/255.0f alpha:1]];


    
    [self.scroll setContentSize:CGSizeMake(SCREEN_WIDTH, 0)];
    
   
    for (int i = 0; i < [array count]; i++) {

        self.button = [UIButton new];
        [self.scroll addSubview:_button];
        [self.button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(@(weakSelf.view.frame.size.width / 5 * i));
            make.size.mas_equalTo(CGSizeMake(weakSelf.view.frame.size.width/5, 30));
        }];
        

        
        self.button.layer.cornerRadius = 10;
        self.button.layer.masksToBounds = YES;
        [_button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal];
        [_button setTitleColor:[UIColor colorWithRed:0/255.0f green:0/255.0f blue:0/255.0f alpha:1] forState:UIControlStateNormal];
        [self.button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_buttonArray addObject:self.button];
      
        [_button release];
    }
    //第一次显示的时候设置button的颜色
    self.button = [self.buttonArray objectAtIndex:0];
    [self.button setBackgroundColor:[UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1]];
    
    
   
    [_scroll release];
    
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    [flow setItemSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT)];
    [flow setMinimumLineSpacing:0];
    [flow setScrollDirection:UICollectionViewScrollDirectionHorizontal];

    
#pragma mark - 横向滑动我们运用了collectionView   然后再每个collectionView里面放tableViewCell 实现纵向的滑动
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake( 0 , SCREEN_WIDTH / 25 * 2, SCREEN_WIDTH, SCREEN_HEIGHT) collectionViewLayout:flow];
    [self.collection setBackgroundColor:[UIColor clearColor]];
    [self.collection registerClass:[CarNewsCollectionViewCell class] forCellWithReuseIdentifier:@"cells"];
    self.collection.delegate = self;
    self.collection.dataSource = self;
    self.collection.pagingEnabled = YES;
    
    [self.view addSubview:self.collection];
    [_collection release];
    [flow release];
    
    
    
}


- (void)buttonAction:(id)sender
{
    UIButton *button = (UIButton *)sender;
    
#pragma mark - 点击后跳转到当前坐标页
    
    [self.collection setContentOffset:CGPointMake(button.frame.origin.x * 5, 0) animated:YES];
    
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    NSMutableArray *arrays = [NSMutableArray array];
    arrays = [self sortUseBlock:self.collectArray];
    [self.collectArray removeAllObjects];
    [self.collectArray addObjectsFromArray:arrays];
    
    
    return [self.collectArray count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    CarNewsCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cells" forIndexPath:indexPath];
    cell.delegate = self;
    SortModel *model = [self.collectArray objectAtIndex:indexPath.item];
    cell.backgroundColor = [UIColor clearColor];
    
    [cell.tableArray removeAllObjects];
    [cell.tableArray addObjectsFromArray:model.myArray];//数组传值
    [cell.tableView reloadData];
    
    return cell;
}


- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    
#pragma mark - 结束正在活动时 给出蓝色块背景(如何让块动态移动？？？)


    if (self.currentState == NO) {
        
        for (int i = 0 ; i < 5; i ++) {
            if (i == self.collection.contentOffset.x / SCREEN_WIDTH) {
                self.button = [self.buttonArray objectAtIndex:i];
                [self.button setBackgroundColor:[UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1]];
                //设置leftBarButtonItem为空且不触发事件
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
                //初始化leftBarButtonItem
                if(i == 2){
                    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"北京市" style:UIBarButtonItemStylePlain target:self action:@selector(area:)];
                }

                
            }
            else
            {
                self.button = [self.buttonArray objectAtIndex:i];
                [self.button setBackgroundColor:[UIColor colorWithRed:238/255.0f green:233/255.0f blue:233/255.0f alpha:1]];
            }
            
        }

    }
    else
    {
        for (int i = 0 ; i < 5; i ++) {
            if (i == self.collection.contentOffset.x / SCREEN_WIDTH) {
                self.button = [self.buttonArray objectAtIndex:i];
               
                [self.button setBackgroundColor:[UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1]];
                //设置leftBarButtonItem为空且不触发事件
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
                //初始化leftBarButtonItem
                if(i == 2){
                    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"北京市" style:UIBarButtonItemStylePlain target:self action:@selector(area:)];
                }

                
            }
            else
            {
                self.button = [self.buttonArray objectAtIndex:i];
                //self.scroll.backgroundColor = [UIColor clearColor];
                [self.button setBackgroundColor:[UIColor clearColor]];
            }

         }
    }
    
    
}
    
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
#pragma mark - 滑动时改变蓝色块（根据坐标来改变,这个和上面的协议的方法不一样，这个在点击滑动页面时才会调用，而上面的是只有在contentOffSet坐标改变的时候动态移动了scrollview时候才会调用）

    if (self.currentState == NO) {
        
        for (int i = 0 ; i < 5; i ++) {
            if (i == self.collection.contentOffset.x / SCREEN_WIDTH) {
                self.button = [self.buttonArray objectAtIndex:i];
                [self.button setBackgroundColor:[UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1]];
                //设置leftBarButtonItem为空且不触发事件
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
                //初始化leftBarButtonItem
                if(i == 2){
                    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"北京市" style:UIBarButtonItemStylePlain target:self action:@selector(area:)];
                }

                
            }
            else
            {
                self.button = [self.buttonArray objectAtIndex:i];
                [self.button setBackgroundColor:[UIColor colorWithRed:238/255.0f green:233/255.0f blue:233/255.0f alpha:1]];
            }
            
        }
        
    }
    else
    {
        for (int i = 0 ; i < 5; i ++) {
            if (i == self.collection.contentOffset.x / SCREEN_WIDTH) {
                self.button = [self.buttonArray objectAtIndex:i];
                
                [self.button setBackgroundColor:[UIColor colorWithRed:220/255.0f green:220/255.0f blue:220/255.0f alpha:1]];
                //设置leftBarButtonItem为空且不触发事件
                self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
                //初始化leftBarButtonItem
                if(i == 2){
                    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"北京市" style:UIBarButtonItemStylePlain target:self action:@selector(area:)];
                }

            }
            else
            {
                self.button = [self.buttonArray objectAtIndex:i];
                self.scroll.backgroundColor = [UIColor clearColor];
                [self.button setBackgroundColor:[UIColor clearColor]];
            }
            
        }
    }
    
}

#pragma mark - 这个是协议回调的方法，实现的是页面的传值 然后进行跳转页面，因为在我们自定义collectionViewCell里不能实现页面的跳转，因此我们就需要用到协议传值的方法把我们需要传到下一页的参数 传到collectionView这个ViewController里面，让ViewController进行页面跳转

- (void)changePage:(NSString *)website
{
    DetailNewsViewController *news = [[DetailNewsViewController alloc] init];
    [self setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self.navigationController pushViewController:news animated:YES];
    news.webSite = website;
    [news release];
    
}

//弹出地区界面
- (void)area:(id)sender{
    MarketAreaViewController *mark = [[MarketAreaViewController alloc]init];
    mark.view.frame = CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width/2, 0);
    [self addChildViewController:mark];
    [self.view addSubview:mark.view];
    mark.mark = mark.view;
    mark.collection = self.collection;
    [UIView animateWithDuration:1 delay:0 options:UIViewAnimationOptionTransitionNone animations:^{
        mark.view.frame = CGRectMake(self.view.frame.size.width/2 , 0, self.view.frame.size.width/2, self.view.frame.size.height);
    } completion:^(BOOL finished) {
        self.collection.userInteractionEnabled = NO;
    }];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.collection reloadData];
    [self changeBackGroundColor];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
